from typing import Callable, ContextManager, Union

from business_processes.opening_account_validation.domain.entity.package import (
    AccountPackage,
)
from business_processes.opening_account_validation.presentation.rest.request import AccountPackageRequest
from business_processes.opening_account_validation.domain.exception.account_package import (
    AccountPackageExistsException,
)
from business_processes.opening_account_validation.infra.repository import (
    PackageRepository
)
from sqlalchemy.orm import Session


class PackageQueryUseCase:
    def __init__(
        self,
        package_processing_repo: PackageRepository,
        db_session: Callable[[], ContextManager[Session]],
    ):
        self.package_processing_repo = package_processing_repo
        self.db_session = db_session

    def create_package_entity(self, package_request: AccountPackageRequest) -> AccountPackage:
        with self.db_session() as session:
            package: Union[
                AccountPackage, None
            ] = self.package_processing_repo.get_package_by_uuid(
                session=session, package_uuid=package_request.package_uuid
            )

            if package:
                raise AccountPackageExistsException

            package = AccountPackage(uuid=package_request.package_uuid, documents=package_request.documents)

            package: Union[
                AccountPackage, None
            ] = self.package_processing_repo.add(
                session=session, instance=package
            )

        return package
